package il.ac.tau.dbcourse.db.reports;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import il.ac.tau.dbcourse.db.Album;
import il.ac.tau.dbcourse.db.DBException;
import il.ac.tau.dbcourse.db.Track;
import il.ac.tau.dbcourse.db.annotations.SQLReport;

@SQLReport(column = "TRACK_ID", table = "MISSING_TRACK")
public class MissingTrack extends AbsReport {
	public MissingTrack(Connection conn) throws SQLException {
		this.conn = conn;
		createStmt();
	}

	private static List<Track> absGetTracks(Connection conn,
			PreparedStatement stmt) throws SQLException {
		ResultSet rs = null;
		try {
			ArrayList<Track> results = new ArrayList<Track>();

			rs = stmt.executeQuery();

			while (rs.next()) {
				Track track = new Track(conn, rs.getLong(1));
				results.add(track);
			}
			return results;
		} finally {
			if (rs != null)
				rs.close();
			if (stmt != null)
				stmt.close();
		}
	}

	public static List<Track> getTracks(Connection conn) throws DBException {

		try {
			PreparedStatement stmt = conn
					.prepareStatement("select track_id from missing_track");
			return absGetTracks(conn, stmt);
		} catch (SQLException e) {
			throw new DBException("Can't get track list - " + e.getMessage());
		}

	}

	public static List<Track> getTracks(Connection conn,Long albumId) throws DBException {
		try {
			PreparedStatement stmt = conn
					.prepareStatement("select track_id from missing_track,track WHERE track.id=missing_track.track_id AND track.album_id=?");
			stmt.setLong(1, albumId);
			return absGetTracks(conn, stmt);
		} catch (SQLException e) {
			throw new DBException("Can't get track list - " + e.getMessage());
		}
	}

	public static List<Track> getTracks(Connection conn,Album album) throws DBException {
		return getTracks(conn,album.getId());
	}

}
